package com.william.jira;

import cn.hutool.setting.dialect.Props;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.SearchResult;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import com.william.jira.model.JiraQueryParams;
import com.william.jira.model.JiraTask;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Jira服务类，用于获取Jira任务信息
 * @author wuyong
 * @date 2024/1/21
 */
@Slf4j
public class JiraService {

    private final String jiraUrl;
    private final String username;
    private final String token;

    /**
     * 构造函数，初始化Jira配置
     */
    public JiraService() {
        try {
            // 使用Hutool的Props工具类加载配置
            Props props = new Props("jira.properties");
            
            this.jiraUrl = props.getStr("jira.url");
            this.username = props.getStr("jira.username");
            this.token = props.getStr("jira.token");
            
        } catch (Exception e) {
            log.error("读取Jira配置文件失败", e);
            throw new RuntimeException("读取Jira配置文件失败: " + e.getMessage());
        }
    }

    /**
     * 获取指定用户的所有任务
     * @param queryParams 查询参数
     * @return 任务列表
     */
    public List<JiraTask> searchTasks(JiraQueryParams queryParams) {
        List<JiraTask> tasks = new ArrayList<>();
        
        try (JiraRestClient restClient = createJiraClient()) {
            String jql = buildJqlQuery(queryParams);
            log.debug("执行JQL查询: {}", jql);
            
            // 执行搜索
            SearchResult searchResult = restClient.getSearchClient()
                    .searchJql(jql)
                    .claim();

            // 转换结果
            for (Issue issue : searchResult.getIssues()) {
                JiraTask task = new JiraTask();
                task.setKey(issue.getKey());
                task.setSummary(issue.getSummary());
                task.setStatus(issue.getStatus().getName());
                task.setAssignee(issue.getAssignee().getName());
                task.setCreated(issue.getCreationDate().toDate());
                task.setUpdated(issue.getUpdateDate().toDate());
                task.setPriority(issue.getPriority().getName());
                tasks.add(task);
            }
        } catch (Exception e) {
            log.error("获取Jira任务失败", e);
            throw new RuntimeException("获取Jira任务失败: " + e.getMessage());
        }
        
        return tasks;
    }

    /**
     * 构建JQL查询语句
     * @param params 查询参数
     * @return JQL查询字符串
     */
    private String buildJqlQuery(JiraQueryParams params) {
        StringBuilder jql = new StringBuilder();
        List<String> conditions = new ArrayList<>();

        // 添加经办人条件
        if (params.getAssignee() != null) {
            conditions.add(String.format("assignee = '%s'", params.getAssignee()));
        }

        // 添加更新时间范围条件
        if (params.getStartDate() != null) {
            conditions.add(String.format("updated >= '%s'", params.getStartDate()));
        }
        if (params.getEndDate() != null) {
            conditions.add(String.format("updated <= '%s'", params.getEndDate()));
        }

        // 添加项目条件
        if (params.getProject() != null) {
            conditions.add(String.format("project = '%s'", params.getProject()));
        }

        // 添加问题类型条件
        if (params.getIssueType() != null) {
            conditions.add(String.format("issueType = '%s'", params.getIssueType()));
        }

        // 添加状态条件
        if (params.getStatus() != null) {
            conditions.add(String.format("status = '%s'", params.getStatus()));
        }

        // 组合所有条件
        jql.append(String.join(" AND ", conditions));

        // 添加排序
        if (params.getOrderBy() != null) {
            jql.append(String.format(" ORDER BY %s %s", 
                params.getOrderBy(), 
                params.isAscending() ? "ASC" : "DESC"));
        }

        return jql.toString();
    }

    /**
     * 创建Jira客户端
     */
    private JiraRestClient createJiraClient() {
        try {
            return new AsynchronousJiraRestClientFactory()
                    .createWithBasicHttpAuthentication(
                            new URI(jiraUrl),
                            username,
                            token);
        } catch (Exception e) {
            log.error("创建Jira客户端失败", e);
            throw new RuntimeException("创建Jira客户端失败: " + e.getMessage());
        }
    }
} 